package com.HeJing.数组的相关算法操作;

/**
 * ClassName: 数组相关查找操作
 * Package: com.HeJing.数组的相关算法操作
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-03-19 18:34
 * @Version: 1.0
 */
public class 数组相关查找操作 {
    public static void main(String[] args){

        /*
        * 1、线性查找
        *   -> 优点: 算法简单
        *   -> 缺点: 效率低，执行的时间复杂度是 O(n)
        *
        * 2、二分查找
        *   -> 优点: 执行效率高，执行的时间复杂度是 O(logn)
        *   -> 缺点: 算法相较于顺序查找而言难一点
        *   -> 前提条件: 序列有序
        * */
        test();

    }

    public static void test(){
        // 线性查找:
        // linearSearch(13);

        // 二分查找:
        binarySearch(130);
    }

    // 线性查找:
    public static void linearSearch(int target){
        int[] arr1 = new int[] {13, 23, 65, 87, 90, 32, 55, 12};

        for(int i = 0; i < arr1.length; i++){
            if (target == arr1[i]){
                System.out.println("找到了目标元素" + target + ", 对应的位置为: " + i);
                return;
            }

        }
        System.out.println("数组中不存在元素: " + target);
    }

    // 二分查找:
    public static void binarySearch(int target){

        int[] arr2 = new int[]{-12, -4, 0, 3, 9, 90, 130, 323, 1392};

        int head = 0;
        int end = arr2.length - 1;
        // int mid = (head + end) / 2;
        while(head <= end){
            int mid = (head + end) / 2;

            if(target == arr2[mid]){
                System.out.println("找到了元素: " + target + ", 其对应的下标为: " + mid);
                return;
            }else if(target > arr2[mid]){
                head = mid + 1;
            }else{
                end = mid - 1;
            }
        }
        System.out.println("数组中并不存在元素: " + target );
    }
}





















